#!/usr/bin/perl -w # for syntax highlighting

use gri_secmgr qw(get_user_name);
use gri_portal_config;

sub mm_portal_chooser($) {
my $action=$_[0];
my $groups=$::GRI_FRONTEND->using_groups();

	my $user_name=get_user_name();
	my ($rc,$err)=$::GRI_FRONTEND->does_user_have_role($user_name,'portal_admin');
	if(! $rc) {
		return "You do not have permissions to access this page.";
	}
	my $portal_dir=$::GRI_FRONTEND->get_global_directory("portals");
	my $dfd;
	@R=();
	my %_portals=();
	opendir($dfd,$portal_dir) or return("ERROR: Can not open directory '$portal_dir': $!");
	while($cline=readdir($dfd)) {
		next if ! -f "$portal_dir/$cline";
		my $aportal=new gri_portal_config("$portal_dir/$cline");
		if(defined($aportal)) {
			$_portals{$cline}=$aportal;
			push @R,$cline;
		}
	}
	closedir($dfd);

	# For each of the portals load in the details ...

	my $s="";
	$row=0;
	my ($users,$reports,$X);
	my @R2=sort {
		my $aportal=$_portals{$a};
		my $bportal=$_portals{$b};
		my $atitle=$aportal->get_title();
		my $btitle=$bportal->get_title();
		lc($atitle) cmp lc($btitle);
			} @R;
	for my $cportal_name (@R2) {
		my $f2=string_to_hex($cportal_name);
		my $cportal=$_portals{$cportal_name}; 
		next if !defined($cportal);
		my $title=$cportal->get_title();
		my $X=0;
		my $X2=0;
		if($action eq "Modify_Users") {
			$users=$cportal->get_users();
			for my $ci (@$users) {
				if(substr($ci,0,2) eq "G:") {
					$X2++;
				} else {
					$X++;
				}
			}
		} else {
			$reports=$cportal->get_reports();
			if(ref($reports)) {
				$X=scalar(@$reports);
			} else {
				my @xx=split(/,/,$reports);
				$X=scalar(@xx);
			}
		}
		my $class="gri_odd";
		$class="gri_even" if $row%2==0;
		$s.="<tr id=$class><td class=gri_cell>$title</td><td class=gri_cell-right>$X</td>";
		if($groups && $action eq "Modify_Users") {
			$s.="<td class=gri_cell-right>$X2</td>";
		}
		my $r2=string_to_hex($x2);
		my $c2=string_to_hex($info[5]);
		$s.="<td class=gri_cell-right>";
		if($action eq "Modify_Users") {
			my $p2=string_to_hex($title);
			$s.=link_to_str("stdlink","Modify User List","form_useraccess_to_portal","portal=$p2");
			if($groups) {
				# Link to modify group list too...
				$s.='&nbsp;&nbsp;&nbsp'.link_to_str("stdlink","Modify Group List","form_groupaccess_to_portal","portal=$p2");
			}
		}
		if($action eq "Modify") {
			my $p2=string_to_hex($title);
			$s.=link_to_str("stdlink","Modify","form_modify_portal","portal=$p2");
		}
		if($action eq "Modify_Subscribed") {
			my $p2=string_to_hex($title);
			$s.=link_to_str("stdlink","Modify Reports List","form_subscribe_to_portal","portal=$p2");
		}
		if($action eq "Delete") {
			my $p2=string_to_hex($title);
			$s.=link_to_str("stdlink","Delete","form_delete_portal_confirm","portal=$p2,filename=$f2");
		}
		$s.="</td></tr>\n";
		$row++;
	}
	return $s;
}

